<template>
  <a-form-model :class="setMode" :model="form" ref="ruleForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" >
    <div class="formBox">
      <a-alert class="formalert" v-if="showAlert"  :message="message" type="warning" show-icon />
      <div class="formRow" :style="[{width:item.width+'px'},setInline]"  v-for="(item,index) in formInfos" :key="index"> 
        <!-- 标准控件 -->
        <!-- input -->
        <a-form-model-item v-if="item.type=='input'" :label="item.label" :prop="item.name">
          <a-input allowClear v-model="form[item.name]" :disabled ="item.isDisabled" :placeholder="item.placeholder"/>
        </a-form-model-item>
        <!-- 带搜索input -->
        <a-form-model-item v-if="item.type=='inputsearch'" :label="item.label" :prop="item.name">
          <a-input-search allowClear v-model="form[item.name]" :disabled ="item.isDisabled" :placeholder="item.placeholder" enter-button @search="inputOnSearch" />
          <!-- <a-input v-model="form[item.name]" :disabled ="item.isDisabled" :placeholder="item.placeholder"/> -->
        </a-form-model-item>
        <!-- 带按钮的input -->
        <a-form-model-item v-if="item.type=='inputbtn'" :label="item.label" :prop="item.name">
          <a-input-search allowClear :placeholder="item.placeholder"  @search="inputbtnOnSearch">
            <a-button slot="enterButton" type="primary">
              {{item.btnname}}
            </a-button>
          </a-input-search>
        </a-form-model-item>
        <!-- number -->
        <a-form-model-item v-if="item.type=='number'" :label="item.label" :prop="item.name">
          <a-input v-model="form[item.name]" :type='item.type' :disabled ="item.isDisabled"  :placeholder="item.placeholder"/>
        </a-form-model-item>
        <!-- textarea -->
        <a-form-model-item v-if="item.type=='textarea'" :label="item.label"   :prop="item.name">
            <a-input  v-model="form[item.name]" type="textarea" :placeholder="item.placeholder"/>
        </a-form-model-item>
        <!-- select -->
        <a-form-model-item  v-if="item.type=='select'" :label="item.label"  :prop="item.name" >
          <a-select v-model="form[item.name]"  :placeholder="item.placeholder" @change="onSelectChange($event,item.link)" >
            <a-select-option v-for="(opt,ind) in item.options" :key="ind" :value="opt.id">
              {{opt.value}}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- radio -->
        <a-form-model-item  v-if="item.type=='radio'" :label="item.label" :prop="item.name">
            <a-radio-group v-model="form[item.name]"  @change="radioOnChange($event,item.name)">
                <a-radio-button v-for="(opt,ind) in item.options" :key="ind" :value="opt.id">
                    {{opt.value}}
                </a-radio-button>
            </a-radio-group> 
        </a-form-model-item>
        <!-- radio2 -->
        <a-form-model-item  v-if="item.type=='radio2'" :label="item.label" :prop="item.name">
            <a-radio-group v-model="form[item.name]" >
                <a-radio v-for="(opt,ind) in item.options" :key="ind" :value="opt.id">
                    {{opt.value}}
                </a-radio>
            </a-radio-group> 
        </a-form-model-item>
        <!-- datatime -->
        <a-form-model-item  v-if="item.type=='datatime'" :label="item.label" :prop="item.name">
          <a-date-picker 
            v-model="form[item.name]"
            @change="(date,dateString)=>dateOnChange(date,dateString,item.name)" />
        </a-form-model-item>
        <!-- datarange -->
        <a-form-model-item  v-if="item.type=='datarange'" :label="item.label"  :prop="item.name"  >
          <a-range-picker
            v-model="form[item.name]"
            :ranges="{}"
            @change="(dates,dateStrings)=>datarangeOnChange(dates,dateStrings,item.name)"
          />
        </a-form-model-item>
        <!-- 复合控件 -->
        <!-- datatimeR -->
        <a-row v-if="item.type=='datatimeR'">
          <a-col :span="labelCol.span"><div class="labels">{{item.label[0]}} <span style="margin: 0 8px 0 2px">:</span> </div></a-col>
          <a-col :span="wrapperCol.span">
           <a-row>
              <a-col :span="8">
              <a-form-model-item   :prop="item.name[0]" :label-col="{ span: 0}" :wrapper-col="{ span: 24}" >
                <a-date-picker 
                  v-model="form[item.name[0]]"
                  :disabled-date="disabledAfterDate"
                  @change="(date,dateString)=>dateOnChange(date,dateString,item.name[0])" />
              </a-form-model-item>
            </a-col>
            <a-col :span="16">
              <a-form-model-item :label="item.label[1]"   :prop="item.name[1]" :label-col="{ span: 4}" :wrapper-col="{ span: 20}" >
                <a-date-picker
                  :disabled ="isDisabled"
                  v-model="form[item.name[1]]"
                  :disabled-date="disabledBeforeDate"
                  @change="(date,dateString)=>dateOnChange(date,dateString,item.name[1])" />
                <a-checkbox style="marginLeft:5px" @change="onChangeLong($event,item.name[1])">
                  长期
                </a-checkbox>
              </a-form-model-item>
            </a-col>
           </a-row>
          </a-col>
        </a-row>
        <!-- uploadimg 单图片上传 -->
        <a-form-model-item  v-if="item.type=='uploadimg'" :label="item.label"  :prop="item.name" >
          <ImgUpload  
            v-model="form[item.name]"
            @change="imgUploaded($event,item.name)">
          </ImgUpload>
        </a-form-model-item>
        <!-- uploadimgs 多图片上传 -->
        <a-form-model-item  v-if="item.type=='uploadimgs'" :label="item.label"  :prop="item.name" >
          <ImgsUpload  
            v-model="form[item.name]"
            @change="imgsUploaded($event,item.name)">
          </ImgsUpload>
        </a-form-model-item>
        <!-- 字典选择 -->
        <a-form-model-item  v-if="item.type=='dicselect'"   :label="item.label"  :prop="item.name" >
          <dictSelects
            :dictCategory="item.dicName?item.dicName:''"
            :showCode="item.showCode"
            :disabled ="item.isDisabled"
            :placeholder="item.placeholder" 
            @change="dicSelectChange($event,item.name)"
            :value="form[item.name]" >
          </dictSelects>
        </a-form-model-item>
        <!-- 业务控件 -->
        <!-- 配送地址Select组件 提供两种模板，使用时将模板放到业务文件，在此添加item -->
        <a-form-model-item v-if="item.type==='selectDemo1'" :label="item.label"  :prop="item.name" >
          <selectDemo1
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            @change="onSelect(arguments,item.name)"
            :value="form[item.name]">
          </selectDemo1>
        </a-form-model-item>
        <a-form-model-item v-if="item.type==='selectDemo2'" :label="item.label"  :prop="item.name" >
          <selectDemo2
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            @change="onSelect(arguments,item.name)"
            :value="form[item.name]">
          </selectDemo2>
        </a-form-model-item>
        <!-- 三级联动选择器 -->
        <a-form-model-item  v-if="item.type=='threeLevelSelect'" :label="item.label"  :prop="item.name[0]" >
          <three-level-select
            :disabled="item.isDisabled"
            :placeholder="item.placeholder" 
            :value="[form[item.name[0]],form[item.name[1]],form[item.name[2]]]"
          >
          </three-level-select>
        </a-form-model-item>
        <!-- 表单中按钮 -->
        <a-form-model-item  v-if="item.type=='buttons'" :label-col="{ span: 0}" :wrapper-col="{ span: 24}" >
          <a-button class="btnInForm" type="primary"  @click="addInfo()">
            {{item.label[0]}}
          </a-button>
        </a-form-model-item>
        <!-- 搜索表单中按钮 -->
        <a-form-model-item v-if="item.type=='searchBtn'"  :label-col="{ span: 0}" :wrapper-col="{ span: 24}">
          <a-button class="searchBtn" type="primary" v-if="item.label[0]"  @click="onSearch('ruleForm')">
            {{item.label[0]}}
          </a-button>
          <a-button class="searchBtn" type="primary"  v-if="item.label[1]"  @click="onReset('ruleForm')">
            {{item.label[1]}}
          </a-button>
        </a-form-model-item>
        <!-- 自定义控件 未测试  -->
        <a-form-model-item v-if="item.type=='cusform'" :label="item.label" :prop="item.name">
          <slot name="cusform" :config="{vmodel:form[item.name],disabled:item.isDisabled,placeholder:item.placeholder}"></slot>
        </a-form-model-item>
      </div> 
      <slot></slot>
    </div>
    <div class="formBtn" :style="btnCusStyle" v-if="isBtn">
        <a-button class="btn" v-if="buttonText[2]" type="primary"  @click="cancel()">
          {{buttonText[2]}}
        </a-button>
        <a-button class="btn" v-if="buttonText[0]" type="primary"  @click="submitForm('ruleForm')">
          {{buttonText[0]}}
        </a-button>
        <a-button class="btn" v-if="buttonText[1]" type="primary"    @click="resetForm('ruleForm')">
          {{buttonText[1]}}
        </a-button>
    </div>
  </a-form-model>
</template>

<script>
import moment from 'moment'
import dictSelects from '@/views/app/common/formSelect/dictSelects.vue'
import ImgUpload from '@/views/app/common/upload/ImgUpload.vue'
import ImgsUpload from '@/views/app/common/upload/ImgsUpload.vue'
import selectDemo1 from '@/views/app/common/formSelect/selectDemo1.vue' 
import selectDemo2 from '@/views/app/common/formSelect/selectDemo2.vue' 
import threeLevelSelect from '@/views/app/biz/common/threeLevelSelect'
export default {
  components:{
    dictSelects,
    ImgUpload,
    ImgsUpload,
    threeLevelSelect,
    selectDemo1,
    selectDemo2
  },
  props:{
    showAlert: {
      default: false,
      require: false,
      type: Boolean
    },
    //表单模式，auto自由撑开，fixed按钮固定 ,search搜索模式
    //fixed模式需给组件设定一个固定高度
        // mode='fixed'
        // style="height:200px"
    // 或者将组件放到一个固定高度的div中
    mode:{
      type:String,
      default:'auto'
    },
    isInline:{
      type:Boolean,
      default:false
    },
    searchStyle:{
      type:Object
    },
    inlineStyle:{
      type:Object
    },
    isBtn: {
      default: true,
      type: Boolean
    },
    message: {
      default: '',
      require: false,
      type: String
    },
    // 表单
    formInfos:{
      type:Array,
    },
    // 数据实体
    formDatas:{
      type:Object
    },
    // 表单规则集
    rules:{
      type:Object
    },
    btnCusStyle:{
      type:Object,
      default:()=>{
        return {
          boxShadow:'0 0 2px #bbb'
        }
      }
    },
    buttonText:{
      type:Array,
      default:()=>{
        return ['提交','放弃',""]
      }
    }
  },
  data(){
    return{  //:awrapperCol="awrapperCol" 
      labelCol: { span:8 },
      wrapperCol:{ span:12 },
      alabelCol:{ span:4 },
      awrapperCol:{span:16},
      form: JSON.parse(JSON.stringify(this.formDatas)),
      forms:{},
      isDisabled:false,
      before100years:null,
      resetobj:JSON.parse(JSON.stringify(this.formDatas)),
      ischange: false,
      //默认水平排列样式
      defaultInline:{
        'float': 'left',
        'width': '50%',
        'min-height': '60px',
      },
      //默认搜索排列样式
      defaultSearch:{
        'float': 'left',
        'width': '150px',
        'min-height': '40px',
        'margin-right': '5px'
      },
    }
  },
  computed:{
    setMode(){
      let mode=this.mode=='fixed'?'fixed-form':'auto-form'
      return [mode]
    },
    setInline(){
      if (this.isInline) {
        if (this.mode=='search') {
          this.labelCol={ span:0 }
          this.wrapperCol={ span:24 }
          return {...this.defaultSearch,...this.searchStyle}
        }else{
          return {...this.defaultInline,...this.inlineStyle}
        }
      }
      
    }
  },
  watch:{
    formDatas:{//深度监听，可监听到对象、数组的变化
        handler(val, oldVal){
          console.log("监听formDatas1",this.form, this.formDatas);
          this.form={...val}
        },
        deep:true //true 深度监听
    }
  },
  mounted(){

  },
  methods:{
    //禁止选择今天之前的日期
    disabledBeforeDate(current) {
      // Can not select days before today and today
      return current && current < moment().endOf('day');
    },
    //禁止选择今天之后的日期
    disabledAfterDate(current) {
      // Can not select days before today and today
      return current && current > moment().endOf('day');
    },
    // 业务组件dicSelect change
    dicSelectChange(val,name){
      this.form[name]=val
      this.$emit("onChangeType",name,val)
      console.log('字典select',val);
    },
    inputOnSearch (val,name) {
      this.form[name]=val
      this.$emit("inputOnSearch",name,val)
    },
    inputbtnOnSearch (val,name) {
      this.form[name]=val
      this.$emit("onChangeType",name,val)
    },
    // 时间变化
    dateOnChange(date,dateString,name) {
      this.form[name] = dateString
      this.$emit("onChangeType",name,dateString)
      console.log(this.forms[name]);
    },
    datarangeOnChange(dates,dateStrings,name){
      //  this.form[name] = dateStrings
      this.form[name] = dateStrings
      this.$emit("onChangeType",name,val)
    },
    // 时间止（包含长期）
    onChangeLong(e,name){
      console.log(e.target.checked);
      let isChecked=e.target.checked
      if(isChecked){
        this.isDisabled=true;
        this.form[name]=moment().add(100, 'Y');
        this.forms[name] = this.form[name].format('YYYY-MM-DD');
      }else{
        this.isDisabled=false;
        this.form[name]=null; 
      }
      this.$emit("onChangeType", name, this.forms[name])
    },
    // selectChange
    onSelectChange(val,link){
      if(link=='1'){//通过val查询二级select
        let link2Item=this.formInfos.find(item=>{//查询第一个二级select,如需查询多个或三级select,在此修改
          return item.link=='2'
        })
        if(link2Item){
          this.form[link2Item.name]=undefined
          link2Item.options=[{id:'0',value:'所有'},{id:'1',value:'A市'},{id:'2',value:'B市'}]
          console.log(link2Item);
        }
        // this.$emit("onChangeType", name, this.forms[name])
      }
    },
    radioOnChange(val,name){//切换时如果表单内容发生变化，则在调用该组件时在onChangeType中重新传入表单信息和数据
        console.log(val,name);
        this.form[name] = val
        this.$emit("onChangeType",name,this.form[name])
    },
    //通用下拉select组件返回函数onSelect，表单name统一绑定列表pid, onChangeType会返回name和选中记录val
    //val包含选中记录的pid和记录全部信息：val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    //例如： { label: '供应商名称', name: 'supplierOrgPid', type: 'supplier', placeholder: '请选择供应商名称' },
    onSelect(val,name){
      console.log(val,name);
      this.form[name]=val[0]
      this.$emit("onChangeType",name,val)
    },
    imgUploaded(imgurl,name){
      this.form[name] = imgurl
      this.$emit("onChangeType",name, imgurl)
      console.log(imgurl);
    },
    imgsUploaded(imgurl,name){
      this.form[name] = imgurl
      this.$emit("onChangeType",name, imgurl)
      console.log(imgurl);
    },
    
    addInfo(){ //点击表单中的添加
      console.log(this.form);
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let submitdata=JSON.parse(JSON.stringify(this.form))
          for (let key in submitdata) {
            for (let keys in this.forms) {
              if (key==keys) {
                submitdata[key]=this.forms[keys]
              }
            }
          }
          console.log('查询中',submitdata);
          this.$emit('onAddInfo',submitdata)
        } else {
          console.log('信息不完整!!');
          return false;
        }
      });
    },
    // 确定
    submitForm(formName) {
      console.log(this.form);
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let submitdata=JSON.parse(JSON.stringify(this.form))
          for (let key in submitdata) {
            for (let keys in this.forms) {
              if (key==keys) {
                submitdata[key]=this.forms[keys]
              }
            }
          }
          console.log('查询中',submitdata);
          this.$emit('onSubmit',submitdata)
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      
    },
    // 重置
    resetForm(formName) {
      this.forms={}
      // this.$refs[formName].resetFields();
      this.form= JSON.parse(JSON.stringify(this.resetobj))
      // console.log("重置表单后",this.form);
      this.$emit("closeModal")
    },
    cancel(){
      this.$emit("onCancel")
    },
    onSearch(formName) {
      this.ischange = false
      let submitdata = JSON.parse(JSON.stringify(this.form))
      for (let key in submitdata) {
        if (submitdata[key]) {
          this.ischange = true
        }
        for (let keys in this.forms) {
          if (key == keys) {
            submitdata[key] = this.forms[keys]
          }
        }
      }
      console.log('查询中', submitdata)
      this.$emit('onFind', submitdata, this.ischange)
    },
    onReset(formName) {
      console.log('重置表单')
      this.$refs[formName].resetFields()
      this.ischange = false
      this.$emit('onFind', this.form, this.ischange)
    },
    
  }
}
</script>

<style scoped>
.formalert{
  margin: auto;
  width: 800px;
}
.fixed-form{
  /* height: 100%; */
  display: flex;
  flex-direction: column;
  overflow: scroll;
}
.auto-form{
  height: auto;
  overflow: scroll;
}
.formBox{
  width: 100%;
  flex: 1;
  overflow-y: scroll;
}
.formBtn{
  height: 60px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items:center;
  /* border: 1px solid #eee; */
}
.formRow{
  min-height: 50px;
  /* border: 1px solid #000; */
  
}
.ant-form-item {
  margin:0;
  /* border: 1px solid #e02; */
}
.btn{
  margin-left: 20px;
}
.searchBtn{
  margin-right: 7px;
}
.labels{
  width: 100%;
  line-height: 40px;
  text-align: right;
}
.btnFixed{
  width: 100%;
  line-height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.btnInForm{
  margin-left: 70%;
}

</style>

//用法:mode：fixed、auto、search
//mode1:fixed：按钮固定,表单内容超出滚动
  // <basic-form
  //     ref="form"
  //     mode='fixed'
  //     style="height:400px" //需给组件设定一个固定高度或者将组件放到一个固定高度的div中
  //     :isBtn="true"        //内置提交按钮配置
  //     :formInfos="d_FormInfo"
  //     :formDatas="d_formDatas"
  //     :rules="d_rules"
  //     ></basic-form>

//mode2:auto：按钮随表单内容超出滚动
  // <basic-form
  //     ref="form"
  //     mode='auto'
  //     :isBtn="true"        //内置提交按钮配置
  //     :formInfos="d_FormInfo"
  //     :formDatas="d_formDatas"
  //     :rules="d_rules"
  //     ></basic-form>
//以上两种模式可设置水平排列方式 :isInline="true"
//表单框排列样式可以传 inlineStyle修改默认样式

//mode3:search：该模式下需配置:isBtn="false" :isInline="true" 
//且s_FormInfo中的搜索配置项label:'',按钮配置项label:['查询','重置']
//表单框排列样式可以传 searchStyle修改默认样式
  // <basic-form
  //     ref="form"
  //     mode='search'
  //     style="height:100px"
  //     :isBtn="false"
  //     :isInline="true"
  //     :formInfos="s_FormInfo"
  //     :formDatas="s_formDatas"
  //     ></basic-form>


//   export const d_FormInfo = [
//   { label: '请输入客户单位社会信用代码', isDisabled: false, name: 'keHushxxdm', type: 'orgsearch', placeholder: '' },
//   { label: '客户编码', name: 'keHudm', isDisabled: false, type: 'uploadimgs', placeholder: ' 客户编码' },
//   { label: '客户社会信用代码',name:'keHushxxdm',type:'uploadimg',placeholder:' 客户社会信用代码'},
//   { label: '客户名称', name: 'keHumc', isDisabled: false, type: 'selectDemo1', placeholder: ' 客户名称' },
//   { label: '客户城市', name: 'chengShi', isDisabled: false, type: 'selectDemo2', placeholder: ' 客户城市' },
//   { label: '客户负责人姓名', name: 'fuZerxm', isDisabled: false, type: 'dicselect',dicName:'zhuCezzt', placeholder: ' 客户负责人姓名' },
//   { label: '客户负责人联系电话', name: 'fuZerdh', isDisabled: false, type: 'input', placeholder: ' 客户负责人联系电话' },
//   { label: '客户联系人姓名', name: 'lianXirxm', isDisabled: false, type: 'input', placeholder: ' 客户联系人姓名' },
//   { label: '客户联系人联系电话', name: 'lianXirdh', isDisabled: true, type: 'input', placeholder: ' 客户联系人联系电话' }
// ]

// export const d_formDatas = {
//   sysSeq: 0,
//   pid: '',
//   keHudm: null,
//   keHuhy: null,
//   keHushxxdm: null,
//   keHuOrgPid: null,
//   keHumc: null,
//   chengShi: null,
//   diZhi: null,
//   fuZerxm: null,
//   fuZerdh: null,
//   lianXirxm: null,
//   lianXirdh: null,
//   zhuangTai: null,
// }
// export const d_rules = {
//   keHushxxdm: [{ required: true, message: '信用代码必填', trigger: 'blur' }],
//   keHumc: [{ required: true, message: '名称必填', trigger: 'blu r' }],
//   fuZerxm: [{ required: true, message: '负责人必填', trigger: 'change' }],
//   lianXirxm: [{ required: true, message: '联系人必填', trigger: 'change' }],
//   lianXirdh: [{ required: true, message: '联系人电话必填', trigger: 'blur' }],
// }

// export const s_FormInfo = [
//   { label: '', name: 'keHumc', isDisabled: false, type: 'selectDemo1', placeholder: ' 客户名称' },
//   { label: '', name: 'chengShi', isDisabled: false, type: 'selectDemo2', placeholder: ' 客户城市' },
//   { label: '', name: 'fuZerxm', isDisabled: false, type: 'dicselect',dicName:'zhuCezzt', placeholder: ' 客户负责人姓名' },
//   { label: '', name: 'fuZerdh', isDisabled: false, type: 'input', placeholder: ' 客户负责人联系电话' },
//   { label: '', name: 'lianXirxm', isDisabled: false, type: 'input', placeholder: ' 客户联系人姓名' },
//   { label: ['查询','重置'], name: 'searchBtn',  type: 'searchBtn', }
// ]